// U选商家管理后台
const Controller = require('egg').Controller;
const sqlConfig = require('../util/sqlConfig')
const err = require('../util/err')
const util = require('../util/util')
const axios = require('axios')
const appid = 'wx069bb9fd47eb702b'      // 小程序ID
const mch_id = '1605857462'             //商户号id
const appSecret = '9bb97baab7f3e893645262f0e5344a9b'    //小程序appSecret
const WX_SHOP_KEY = 'liuhu666liuhu666liuhu666liuhu666'  //商户平台设置的密钥key
const fs = require('fs')
const xml2js = require('xml2js')

const parser = require("fast-xml-parser");  
let j2xParser = parser.j2xParser
const j2xparser = new j2xParser();
const moment = require('moment')

class UBusinessManageController extends Controller {
    //  获取校园管理员列表  
    async uSchoolManageList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uSchoolManageList(r_body))
        for (let index = 0; index < list.length; index++) {
            const element = list[index];
            let data2 = await mysql.select('uSchool', {
                where: { id: element.schoolId}
            })
            element.schoolName = util.handelData(data2)[0].name
            element.key = element.manageId
        }
        const total = util.handelData(await mysql.query(sqlConfig.uSchoolManageTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
    // 新增校园管理员
    async uSchoolManageAdd() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {userName,password,name,schoolId,type} = r_body
        let json
        if(type===1){
            json = { userName}
        }else if(type===2){
            json = { userName,schoolId}
        }else if(type===3){
            json = { userName,schoolId}
        }else if(type===4){
            json = { userName,schoolId}
        }
        const data = await mysql.select('loginManage', {
            where: json
        })
        if(data.length){
            ctx.body = err.err7
        }else{
            await mysql.insert('loginManage', {
                userName,password,name,schoolId,type:type
            })
            await mysql.insert('banner', {
                uSchoolId:schoolId
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        }
    }
    // 删除校园管理员
    async uSchoolManageDelete() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {manageId} = r_body
        await mysql.delete('loginManage', {
            manageId
        });
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 编辑校园管理员
    async uSchoolManageUpdate() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {password,name,manageId} = r_body
        let params
        if(password){
            params = {
                password,
                name
            }
        }else{
            params = {
                name
            }
        }
        await mysql.update('loginManage',params ,{
            where: {
                manageId
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    //  获取校园管理员列表  
    async uSchoolList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uSchoolList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.uSchoolTotal()))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
     // 新增校园入驻/u/schoolManageList
    async uSchoolAdd() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {name} = r_body
        const data = await mysql.select('uSchool', {
            where: { name}
        })
        if(data.length){
            ctx.body = err.err8
        }else{
            await mysql.insert('uSchool', {
                name
            })
            const data2 = await mysql.select('uSchool', {
                columns:['id'],
                where: { name}
            })
            const uSchoolId  = data2[0].id
            await mysql.insert('concat', {
                uSchoolId
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        }
    }
    // 删除校园入驻
    async uSchoolDelete() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id} = r_body
        await mysql.delete('uSchool', {
            id
        });
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 编辑校园入驻
    async uSchoolUpdate() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,name} = r_body
        let params = {
            name
        }
        await mysql.update('uSchool',params,{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 新增商铺 
    async uBusinessManageAdd() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {manageId,uSchoolId,userName,businessManageId,title,url,src,uTypeId,uType,uSubType,tel,address,endTime,businessTime,buyNotice,detail,openid,scale,wxName,ord,topNum} = r_body
        await mysql.insert('uBusiness', {
            manageId,uSchoolId,userName,businessManageId,url,src,title,uTypeId,uType,uSubType,tel,address,endTime,businessTime,buyNotice,detail,openid,scale,wxName,ord,topNum,time:moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 商铺列表
    async uBusinessManageList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uBusinessManageList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.uBusinessManageTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
     // 删除商铺
    async uBusinessManageDelete() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id} = r_body
        await mysql.delete('uBusiness', {
            id
        });
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 编辑商铺
    async uBusinessManageUpdate() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,title,url,src,uTypeId,uType,uSubType,tel,address,endTime,businessTime,buyNotice,detail,openid,scale,wxName,name,ord,topNum} = r_body
        let params = {
            title,url,src,uTypeId,uType,uSubType,tel,address,endTime,businessTime,buyNotice,detail,openid,wxName,scale,name,ord,topNum
        }
        await mysql.update('uBusiness',params,{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 上架/下架商铺
    async uBusinessManageGround() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,isGrounding} = r_body
        let params = {
            isGrounding
        }
        await mysql.update('uBusiness',params,{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 商铺排序
    async uBusinessManageOrd() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,ord} = r_body
        let params = {
            ord
        }
        await mysql.update('uBusiness',params,{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 商铺类型列表
    async uTypeList() {
        const { ctx, app } = this;
        const { mysql } = app
        const data = await mysql.select('uType')
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 爆款推荐列表
    async uTopList() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const {uSchoolId} = r_body
        const data = await mysql.select('uTop',{
            where:{
                uSchoolId
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 进入爆款区
    async uBusinessEnterTop() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,topNum} = r_body
        let params = {
            topNum
        }
        await mysql.update('uBusiness',params,{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 新增套餐
    async uTicketAdd() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {uSchoolId,uBusinessId,content,price,priceOld,numTotal,src} = r_body
        await mysql.insert('uTicket', {
            uSchoolId,uBusinessId,content,price,priceOld,numTotal,src
        })
        await mysql.update('uBusiness',{
            isGrounding:1
        },{
            where: {
                id:uBusinessId
            }
        })
        const _data = await mysql.select('uTicket', {
            where: { uBusinessId}
        })
        // 处理uBusiness表的价格和数量
        if(_data.length){
            let [num,numTotal] = [0,0]
            _data.map(item=>{
                num+=item.num,
                numTotal+=item.numTotal
            })
            const _dataNew = util.sortArr(_data,'price')[util.sortArr(_data,'price').length-1]
            const {price,priceOld} = _dataNew
            await mysql.update('uBusiness',{
                isGrounding:1,
                price,
                priceOld,
                num,
                numTotal
            },{
                where: {
                    id:uBusinessId
                }
            })
        }
        
        
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 套餐列表
    async uTicketList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uTicketList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.uTicketTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
    // 编辑套餐
    async uTicketUpdate() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,content,price,priceOld,numTotal,uBusinessId,src} = r_body
        let params = {
            content,price,priceOld,numTotal,src
        }
        await mysql.update('uTicket',params,{
            where: {
                id
            }
        })
        // 处理uBusiness表的价格和数量
        const _data = await mysql.select('uTicket', {
            where: { uBusinessId}
        })
        if(_data.length){
            let [num,numTotal] = [0,0]
            _data.map(item=>{
                num+=item.num,
                numTotal+=item.numTotal
            })
            const _dataNew = util.sortArr(_data,'price')[util.sortArr(_data,'price').length-1]
            const {price,priceOld} = _dataNew
            await mysql.update('uBusiness',{
                isGrounding:1,
                price,
                priceOld,
                num,
                numTotal
            },{
                where: {
                    id:uBusinessId
                }
            })
        }
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 删除套餐
    async uTicketDelete() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,uBusinessId} = r_body
        await mysql.delete('uTicket', {
            id
        })
        const num = util.handelData(await mysql.query(sqlConfig.uTicketNum(r_body)))[0]['count(*)']
        if(num<1){
            await mysql.update('uBusiness',{
                isGrounding:0
            },{
                where: {
                    id:uBusinessId
                }
            })
        }

        // 处理uBusiness表的价格和数量
        const _data = await mysql.select('uTicket', {
            where: { uBusinessId}
        })
        if(_data.length){
            let [num,numTotal] = [0,0]
            _data.map(item=>{
                num+=item.num,
                numTotal+=item.numTotal
            })
            const _dataNew = util.sortArr(_data,'price')[util.sortArr(_data,'price').length-1]
            const {price,priceOld} = _dataNew
            await mysql.update('uBusiness',{
                isGrounding:1,
                price,
                priceOld,
                num,
                numTotal
            },{
                where: {
                    id:uBusinessId
                }
            })
        }
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }

    // 订单列表
    async uOrderManageList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uOrderManageList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.uOrderManageTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }

    // 未使用订单退款
    async uOrderToPay() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id} = r_body
        await mysql.update('uOrder',{
            status:5
        },{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }


    //  获取爆款区列表  
    async topAreaList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.topAreaList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.topAreaTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
     // 新增爆款区
    async topAreaAdd() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {name,uSchoolId} = r_body
        const data = await mysql.select('uTop', {
            where: { name,uSchoolId}
        })
        if(data.length){
            ctx.body = err.err9
        }else{
            await mysql.insert('uTop', {
                name,
                uSchoolId
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        }
    }
    // 删除爆款区
    async topAreaDelete() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id} = r_body
        await mysql.delete('uTop', {
            id
        });
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 编辑爆款区
    async topAreaUpdate() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {id,name} = r_body
        let params = {
            name
        }
        await mysql.update('uTop',params,{
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }

    // 商家订单列表
    async uOrderBusList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uOrderBusList(r_body))
        // 连表查询
        for (let index = 0; index < list.length; index++) {
            const element = list[index];
            let data2 = await mysql.select('uBusiness', {
                where: { id: element.uBusinessId}
            })
            let data3 = await mysql.select('login', {
                where: { loginId: element.loginId}
            })
            element.uBusinessInfo = data2.length?data2[0]:{}
            element.loginInfo = data3.length?data3[0]:{}
            element.key=index
        }
        const total = util.handelData(await mysql.query(sqlConfig.uOrderBusTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }

    // 商家订单列表(超时)
    async uOrderBusListTimeout() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uOrderBusListTimeout(r_body))
        // 连表查询
        for (let index = 0; index < list.length; index++) {
            const element = list[index];
            let data2 = await mysql.select('uBusiness', {
                where: { id: element.uBusinessId}
            })
            let data3 = await mysql.select('login', {
                where: { loginId: element.loginId}
            })
            element.uBusinessInfo = data2.length?data2[0]:{}
            element.loginInfo = data3.length?data3[0]:{}
            element.key=index
        }
        const total = util.handelData(await mysql.query(sqlConfig.uOrderBusTotalTimeout(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
    // 校园管理者人工分账订单列表
    async uOrderCheck() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uOrderCheckList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.uOrderCheckTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
    // 核算订单
    async uOrderCheckUptate() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {ids} = r_body
        let params = {
            isCheck:2
        }
        for(let i=0;i<ids.length;i++){
            await mysql.update('uOrder',params,{
                where: {
                    id:ids[i]
                }
            })
        }
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 商家人工分账订单列表
    async uOrderCheckManage() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.uOrderCheckManageList(r_body))
        list.map((item,i)=>{
            item.key=i
        })
        const total = util.handelData(await mysql.query(sqlConfig.uOrderCheckManageTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
               list,
               total
            }
        }
    }
    // h5验券 查询该商铺用户名（手机号下）下所有 manageId,判断该券是否属于商铺
    async vertifyTicket() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {userName,manageId,ticketCode} = r_body
        if (r_body) {
            const data = await mysql.select('loginManage',{
                where:{
                    userName,
                    manageId
                }
            })
            if(data.length){
                const dataOrder = await mysql.select('uOrder', {
                    where: {
                        ticketCode
                    }
                })
                const {uBusinessId} = dataOrder[0]
                const dataBusiness = await mysql.select('uBusiness', {
                    where: {
                        id:uBusinessId
                    }
                })
                const {endTime} = dataBusiness[0]
                if((new Date()).getTime()<(new Date(endTime)).getTime()){
                    const result = await mysql.update('uOrder',{
                        status:4
                    } ,{
                        where: {
                            ticketCode
                        }
                    })
                    if(result.affectedRows === 1){
                        ctx.body = {
                            code: 200,
                            msg: 'SUCCESS',
                            data:{}
                        }
                    }else{
                        ctx.body = err.err11
                    }
                }else{
                    ctx.body = err.err13
                }
                

                
                
            }else{
                ctx.body = err.err10
            }
            
        } else {
            ctx.body = err.err1
        }
    }
    async version() {
        const { ctx, app } = this;
        const { mysql } = app
        const data = await mysql.select('version')
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data[0].status
        }
    }
    async versionUpdate() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        await mysql.update('version', body, {
            where: {
                id:1
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }

    // 添加分账接收方
    async addReciver() {
        const CryptoJS = require('crypto-js/crypto-js')
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const {wxName,openid} = r_body
        const params = {
            appid,
            mch_id,
            nonce_str: util.makeCode(30),
            sign_type:'HMAC-SHA256',
            receiver:JSON.stringify({
                type:'PERSONAL_OPENID',
                account:openid,
                name:wxName,
                relation_type:'SERVICE_PROVIDER'
            })
        }
        const stringSignTemp =  util.getWXSingSha(params,WX_SHOP_KEY)
        const hash = CryptoJS.HmacSHA256(stringSignTemp, WX_SHOP_KEY)
        const sign = CryptoJS.enc.Hex.stringify(hash)
        params.sign = sign
        const obj = {
            xml: params
        }
        const xml = j2xparser.parse(obj)
        await axios.post('https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver', xml, {
            headers: {
                "Content-Type": "application/xml"
            },
        }).then(function (res) {
        }).catch(function (error) {
            ctx.body = err.err3(error)
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data:{}
        }
    }
    // 分账
    async handleAccount() {
        const CryptoJS = require('crypto-js/crypto-js')
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const {ticketCode} = r_body
        const data = await mysql.select('uOrder', {
            where: {
                ticketCode
            }
        })
        if(data.length){
            const {orderNum,uSchoolId,price,uBusinessId} = data[0]

            // 查询openid，分账比例
            const data2 = await mysql.select('uBusiness', {
                where: {
                    id:uBusinessId
                }
            })
            const {openid,scale} = data2[0]
            let transaction_id = ''
            // 查询微信支付订单号
            const params1 = {
                appid,
                mch_id,
                nonce_str: util.makeCode(30),
                sign_type:'HMAC-SHA256',
                out_trade_no:orderNum
            }
            const stringSignTemp1 =  util.getWXSingSha(params1,WX_SHOP_KEY)
            const hash1 = CryptoJS.HmacSHA256(stringSignTemp1, WX_SHOP_KEY)
            const sign1 = CryptoJS.enc.Hex.stringify(hash1)
            params1.sign = sign1
            const obj1 = {
                xml: params1
            }
            const xml1 = j2xparser.parse(obj1)
            await axios.post('https://api.mch.weixin.qq.com/pay/orderquery', xml1, {
            headers: {
                "Content-Type": "application/xml"
                    },
                }).then(function (res) {
                    xml2js.parseString(res.data, (err, result) => {
                        if (err) {
                            ctx.throw(422, err)
                        }
                        transaction_id = result.xml.transaction_id[0]
                    })
                   
                }).catch(function (error) {
                    ctx.body = err.err3(error)
                })
            
            // 分账
            const params = {
                appid,
                mch_id,
                nonce_str: util.makeCode(30),
                transaction_id,
                out_order_no:`P${new Date().getTime()}sh${uSchoolId}`,
                sign_type:'HMAC-SHA256',
                receivers:JSON.stringify([
                    {
                        type:'PERSONAL_OPENID',
                        account:openid,
                        amount:parseInt(price*scale),
                        description:'U你校园商户结算到账'
                    }
                ])
            }
            const stringSignTemp =  util.getWXSingSha(params,WX_SHOP_KEY)
            const hash = CryptoJS.HmacSHA256(stringSignTemp, WX_SHOP_KEY)
            const sign = CryptoJS.enc.Hex.stringify(hash)
            params.sign = sign
            const obj = {
                xml: params
            }
            const xml = j2xparser.parse(obj)
            const res = await ctx.curl(
                "https://api.mch.weixin.qq.com/secapi/pay/profitsharing",
                {
                 // 需要使用证书apiclient_cert
                 cert: fs.readFileSync(`${__dirname}/cert/apiclient_cert.pem`),
                 key: fs.readFileSync(`${__dirname}/cert/apiclient_key.pem`),
                 method: "post",
                 data: xml,
                }
               )
            const datastring = res.data.toString()
            xml2js.parseString(datastring, (err, result) => {
                if (err) {
                ctx.throw(422, err)
                }
                ctx.body = {
                    code: 200,
                    msg: 'SUCCESS',
                    data:result
                }
            })
              
            
        }else{
            ctx.body = err.err11
        }
        
    }
    // 分账查询
    async handleAccountResult() {
        const CryptoJS = require('crypto-js/crypto-js')
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const params = {
            mch_id,
            transaction_id:'4200000990202104197182394038',
            nonce_str: util.makeCode(30),
            sign_type:'HMAC-SHA256',
        }
        const stringSignTemp =  util.getWXSingSha(params,WX_SHOP_KEY)
        const hash = CryptoJS.HmacSHA256(stringSignTemp, WX_SHOP_KEY)
        const sign = CryptoJS.enc.Hex.stringify(hash)
        params.sign = sign
        const obj = {
            xml: params
        }
        const xml = j2xparser.parse(obj)
        await axios.post('https://api.mch.weixin.qq.com/pay/profitsharingorderamountquery', xml, {
            headers: {
                "Content-Type": "application/xml"
            },
        }).then(function (res) {
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data:res.data
            }
        }).catch(function (error) {
            ctx.body = err.err3(error)
        })
        
    }


    // 临时分账
    // async handleAccountOne() {
    //     const CryptoJS = require('crypto-js/crypto-js')
    //     const { ctx, app } = this;
    //     const { mysql } = app
    //     const r_body = ctx.request.body;
    //     const {orderNum,amount} = r_body    
    //     let transaction_id = ''
    //     // 查询微信支付订单号
    //     const params1 = {
    //         appid,
    //         mch_id,
    //         nonce_str: util.makeCode(30),
    //         sign_type:'HMAC-SHA256',
    //         out_trade_no:orderNum
    //     }
    //     const stringSignTemp1 =  util.getWXSingSha(params1,WX_SHOP_KEY)
    //     const hash1 = CryptoJS.HmacSHA256(stringSignTemp1, WX_SHOP_KEY)
    //     const sign1 = CryptoJS.enc.Hex.stringify(hash1)
    //     params1.sign = sign1
    //     const obj1 = {
    //         xml: params1
    //     }
    //     const xml1 = j2xparser.parse(obj1)
    //     await axios.post('https://api.mch.weixin.qq.com/pay/orderquery', xml1, {
    //     headers: {
    //         "Content-Type": "application/xml"
    //             },
    //         }).then(function (res) {
    //             xml2js.parseString(res.data, (err, result) => {
    //                 if (err) {
    //                     ctx.throw(422, err)
    //                 }
    //                 transaction_id = result.xml.transaction_id[0]
    //             })
               
    //         }).catch(function (error) {
    //             ctx.body = err.err3(error)
    //         })
        
    //     // 分账
    //     const params = {
    //         appid,
    //         mch_id,
    //         nonce_str: util.makeCode(30),
    //         transaction_id,
    //         out_order_no:`P${new Date().getTime()}ns12`,
    //         sign_type:'HMAC-SHA256',
    //         receivers:JSON.stringify([
    //             {
    //                 type:'PERSONAL_OPENID',
    //                 account:'o43235ONa5WTJwNzollD8I2MolDg',
    //                 amount:parseInt(amount),
    //                 description:'新生专区分账测试'
    //             }
    //         ])
    //     }
    //     const stringSignTemp =  util.getWXSingSha(params,WX_SHOP_KEY)
    //     const hash = CryptoJS.HmacSHA256(stringSignTemp, WX_SHOP_KEY)
    //     const sign = CryptoJS.enc.Hex.stringify(hash)
    //     params.sign = sign
    //     const obj = {
    //         xml: params
    //     }
    //     const xml = j2xparser.parse(obj)
    //     const res = await ctx.curl(
    //         "https://api.mch.weixin.qq.com/secapi/pay/profitsharing",
    //         {
    //          // 需要使用证书apiclient_cert
    //          cert: fs.readFileSync(`${__dirname}/cert/apiclient_cert.pem`),
    //          key: fs.readFileSync(`${__dirname}/cert/apiclient_key.pem`),
    //          method: "post",
    //          data: xml,
    //         }
    //        )
    //     const datastring = res.data.toString()
    //     xml2js.parseString(datastring, (err, result) => {
    //         if (err) {
    //         ctx.throw(422, err)
    //         }
    //         ctx.body = {
    //             code: 200,
    //             msg: 'SUCCESS',
    //             data:result
    //         }
    //     })
        
    // }

}



module.exports = UBusinessManageController;